import time
import uuid
import ctypes
import json
import base64
import random
import requests
from urllib.parse import unquote_plus, quote_plus


def r(data_string):
    def int_overflow(val):
        maxint = 2147483647
        if not -maxint - 1 <= val <= maxint:
            val = (val + (maxint + 1)) % (2 * (maxint + 1)) - maxint - 1
        return val

    def unsigned_right_shitf(n, i):
        # 数字小于0，则转为32位无符号uint
        if n < 0:
            n = ctypes.c_uint32(n).value
        # 正常位移位数是为正数，但是为了兼容js之类的，负数就右移变成左移好了
        if i < 0:
            return -int_overflow(n << abs(i))
        # print(n)
        return int_overflow(n >> i)

    char_list = []
    aae = ['K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'U', 'V',
           'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'e', 'f', 'g', 'h',
           'i', 'j', 'k', 'l', 'm', 'n', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/']
    bArr = data_string.encode('utf-8')
    for i in range(0, len(bArr), 3):
        bArr2 = [None for i in range(4)]
        b2 = 0
        for i2 in range(0, 3):
            i3 = i + i2
            if i3 <= len(bArr) - 1:
                bArr2[i2] = b2 | unsigned_right_shitf((bArr[i3] & 255), ((i2 * 2) + 2))
                b2 = unsigned_right_shitf(((bArr[i3] & 255) << (((2 - i2) * 2) + 2)) & 255, 2)
            else:
                bArr2[i2] = b2
                b2 = 64
        bArr2[3] = b2
        for i4 in range(4):
            if bArr2[i4] <= 63:
                char_list.append(aae[bArr2[i4]])
            else:
                char_list.append("=")

    return "".join(char_list)


def encode_cipher(cipher_dict):
    for k, v in cipher_dict.items():
        cipher_dict[k] = r(v)


def gen_uuid():
    uid = str(uuid.uuid4())
    return uid.replace("-", "")


def gen_cipher_ep(uid, aid, open_udid, ts):
    cipher_dict = {
        "area": "DV8nDNrpCzO4D18zDNSnCK==",
        "d_model": "Pixel2XL",
        "wifiBssid": "unknown",
        "osVersion": "10",
        "d_brand": "Google",
        "screen": "2712*1440",
        "uuid": uid,
        "aid": aid,
        "openudid": open_udid,
    }
    encode_cipher(cipher_dict)
    data_dict = {
        "hdid": "JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw=",
        "ts": ts,
        'ridx': -1,
        'cipher': cipher_dict,
        'ciphertype': 5,
        "version": "1.2.0",
        'appname': "com.jingdong.app.mall"
    }
    ep = json.dumps(data_dict, separators=(',', ':'))

    return ep


def gen_sign(function_id, body, uid):
    import subprocess
    cmd = f"java -jar  unidbg-0.9.7.jar {function_id} '{body}' {uid}"
    signature = subprocess.check_output(cmd, shell=True, cwd="unidbg_parent_jar")
    data_string = signature.strip().decode('utf-8').split("\n")[-1]
    # st=1663856983680&sign=989f981f828bb5e0120edba9f6b8e7b6&sv=111
    return {item.split("=")[0]: item.split("=")[1] for item in data_string.split("&")}


def run():
    aid = gen_uuid()
    uid = aid
    open_udid = aid
    ts = int(time.time() * 1000)
    ep = gen_cipher_ep(aid, uid, open_udid, ts)

    function_id = "backupKeywords"
    body = '{"keyword":"内存条"}'

    # {sign:xx,sv:xxx,st:xxx}
    sign_dict = gen_sign(function_id, body, uid)

    res = requests.post(
        url="https://api.m.jd.com/client.action",
        params={
            "functionId": function_id,
            "clientVersion": "10.4.4",
            "build": "93860",
            "client": "android",
            "partner": "tencent",
            "sdkVersion": "29",
            "lang": "en_US",
            "harmonyOs": "0",
            "networkType": "wifi",
            "uemps": "0-2",
            "ext": '{"prstate":"0","pvcStu":"1"}',
            "ef": "1",
            "ep": ep,
            "st": sign_dict['st'],
            "sign": sign_dict['sign'],
            "sv": sign_dict['sv'],
        },
        data='body={}&'.format(quote_plus(body)),
        headers={
            "user-agent": "okhttp/3.12.1;jdmall;android;version/10.4.4;build/93860;",
            'content-type': "application/x-www-form-urlencoded; charset=UTF-8"
        },
    )

    print(res.text)


if __name__ == '__main__':
    run()
